#include "text_to_wav.h"

unsigned char *bitmask(char letter)
{
  unsigned char *res = NULL;

  res = malloc(8 * sizeof(char));
  res[0] = letter & 0x80;
  res[1] = letter & 0x40;
  res[2] = letter & 0x20;
  res[3] = letter & 0x10;
  res[4] = letter & 0x08;
  res[5] = letter & 0x04;
  res[6] = letter & 0x02;
  res[7] = letter & 0x01;

  return (res);

}

char **allocation(char *music_file)
{
  char **name_file = NULL;

  name_file = malloc(3 * sizeof (char *));
  name_file[0] = music_file;
  name_file[1] = "header.txt";
  name_file[2] = "binary.txt";

  return (name_file);

}


/* function use to convert our text into binary and hide this in .wav*/
/* need location of music file and text file */
/* finally create temp.wav, sound result with text hidding */

void	change(char *music_file,char *text_file)
{
  char **name_file = NULL;
  int i, j = 0, mod = 0 , k = 0;
  FILE *file_binary = NULL;
  unsigned char *let = NULL , var;

  name_file = allocation(music_file);
  file_binary = fopen(name_file[2],"r+");
  mod = header(name_file[1]);
  k = (mod / 8) - 1;
  while (text_file[j] != '\0')
  {
    let = bitmask(text_file[j]);
    for (i = 0 ; i <= 7 ; ++i)
    {
      fseek(file_binary , k , SEEK_CUR);
      fread(&var , sizeof (char), 1 , file_binary);
      if (let[i] == 0)
	var = var & 0xFE;
      else
	var = var | 0x01;
      fseek(file_binary, -1 , SEEK_CUR);
      fwrite(&var, sizeof (char), 1, file_binary);
    }

    free(let);
    ++i;
    ++j;
  }
  for (i = 0 ; i <= 7 ; ++i)
  {
    fseek(file_binary , k , SEEK_CUR);
    fread(&var , sizeof (char) , 1, file_binary);
    var = var | 0x01;
    fseek(file_binary, -1 , SEEK_CUR);
    fwrite(&var, sizeof (char), 1, file_binary);
  }
  free(name_file);
  fclose(file_binary);
}
